package basicobject

import (
	"strconv"
	"yizhuoyan/go-study/pdfgo/handyio"
)

type Real struct {
	value float64
}

func (this *Real) ValueFloat64() float64 {
	return this.value
}
func (this *Real) Serialize(w handyio.PdfRawWriter) error {
	w.WriteBytes([]byte(strconv.FormatFloat(this.value, 'g', 10, 64)))
	return nil
}
func (this *Real) UnSerialize(r handyio.PdfRawReader) error {
	if r.NextByteEquals('+') {
		rst, err := this.unSerializeNoSign(r)
		if err != nil {
			return err
		}
		this.value = rst
		return nil
	}
	if r.NextByteEquals('-') {
		rst, err := this.unSerializeNoSign(r)
		if err != nil {
			return err
		}
		this.value = -rst
		return nil
	}
	rst, err := this.unSerializeNoSign(r)
	if err != nil {
		return err
	}
	this.value = rst

	return nil
}

func (this *Real) unSerializeNoSign(r handyio.PdfRawReader) (float64, error) {
	hasPoint := false
	startAt := r.IndexCurrent()
	rst := r.NextBytes(func(b byte) int {
		switch b {
		case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
			return handyio.ReadNext
		case '.':
			if hasPoint {
				//忽略多余的点
				return handyio.ReadByteSkip
			}
			hasPoint = true
			return handyio.ReadNext
		}
		//其他字符结束
		return handyio.ReadStop
	})
	if len(rst) == 0 {
		return 0, r.NotSupport("")
	}
	v, err := strconv.ParseFloat(string(rst), 64)
	if err != nil {
		_ = r.IndexMoveTo(startAt)
		return 0, err
	}
	return v, nil
}
